package com.foosun.core.util;


/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-7-30
 * Time: 下午3:03
 * To change this template use File | Settings | File Templates.
 */

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;

/**
 * 25   * 利用zxing开源工具生成二维码QRCode
 * 26   *
 * 27   * @date 2013-04-11
 * 28   * @author lxl
 * 29   *
 * 30
 */
public class QrUtil {
    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 36       * @param args
     * 37
     */
    public static void main(String[] args) {
        QrUtil test = new QrUtil();
        File file = new File("D://test.png");
        /**
         42           * 在com.google.zxing.MultiFormatWriter类中，定义了一些我们不知道的码,二维码只是其中的一种<br>
         43           * public BitMatrix encode(String contents,
         44                            BarcodeFormat format,
         45                            int width, int height,
         46                            Map<EncodeHintType,?> hints) throws WriterException {
         47              Writer writer;
         48              switch (format) {
         49                case EAN_8:
         50                  writer = new EAN8Writer();
         51                  break;
         52                case EAN_13:
         53                  writer = new EAN13Writer();
         54                  break;
         55                case UPC_A:
         56                  writer = new UPCAWriter();
         57                  break;
         58                case QR_CODE:  //这里是二维码
         59                  writer = new QRCodeWriter();
         60                  break;
         61                case CODE_39:
         62                  writer = new Code39Writer();
         63                  break;
         64                case CODE_128:  //这个可以生成
         65                  writer = new Code128Writer();
         66                  break;
         67                case ITF:
         68                  writer = new ITFWriter();
         69                  break;
         70                case PDF_417:  //这个可以生成
         71                  writer = new PDF417Writer();
         72                  break;
         73                case CODABAR:
         74                  writer = new CodaBarWriter();
         75                  break;
         76                default:
         77                  throw new IllegalArgumentException("No encoder available for format " + format);
         78              }
         79              return writer.encode(contents, format, width, height, hints);
         80            }
         81
         82           */
        test.encode("中文二维码信息", file, BarcodeFormat.QR_CODE, 200, 200, null);
        // test.decode(file);
    }

    /**
     * 88       * 生成QRCode二维码<br>
     * 89       * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
     * 90       *  static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
     * 91       *  修改为UTF-8，否则中文编译后解析不了<br>
     * 92
     */

    public static OutputStream genQRCode(OutputStream out, String contents, int width, int height) {
        try {
            BarcodeFormat format = BarcodeFormat.QR_CODE;
            contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");//如果不想更改源码，则将字符串转换成ISO-8859-1编码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
            BufferedImage image = toBufferedImage(bitMatrix);
            ImageIO.write(image, "png", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    public void encode(String contents, File file, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
        try {
            contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");//如果不想更改源码，则将字符串转换成ISO-8859-1编码

            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
            writeToFile(bitMatrix, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 105       * 生成二维码图片<br>
     * 106       *
     * 107       * @param matrix
     * 108       * @param format
     * 109       *            图片格式
     * 110       * @param file
     * 111       *            生成二维码图片位置
     * 112       * @throws IOException
     * 113
     */
    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        ImageIO.write(image, format, file);
    }

    /**
     * 120       * 生成二维码内容<br>
     * 121       *
     * 122       * @param matrix
     * 123       * @return
     * 124
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 138       * 解析QRCode二维码
     * 139
     */
    @SuppressWarnings("unchecked")
    public void decode(File file) {
        try {
            BufferedImage image;
            try {
                image = ImageIO.read(file);
                if (image == null) {
                    System.out.println("Could not decode image");
                }
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result result;
                @SuppressWarnings("rawtypes")
                Hashtable hints = new Hashtable();
                //解码设置编码方式为：utf-8
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                result = new MultiFormatReader().decode(bitmap, hints);
                String resultStr = result.getText();
                System.out.println("解析后内容：" + resultStr);
            } catch (IOException ioe) {
                System.out.println(ioe.toString());
            } catch (ReaderException re) {
                System.out.println(re.toString());
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}